<template>
  <div class="admin-profile">
    <div class="profile-header">
      <div class="avatar-container">
        <el-avatar :size="100" :src="avatarUrl" @error="handleAvatarError">
          <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"/>
        </el-avatar>
        <div class="upload-btn">
          <el-upload
            class="avatar-uploader"
            action="/api/adminProfile/uploadAvatar"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <el-button size="small" type="primary">更换头像</el-button>
          </el-upload>
        </div>
      </div>
      <div class="admin-info">
        <h2>{{ adminInfo.name || '管理员' }}</h2>
        <p class="admin-role">{{ getRoleName(adminInfo.roleId) }}</p>
        <p class="signature">{{ profile.signature || '系统管理员' }}</p>
      </div>
    </div>

    <el-tabs v-model="activeTab">
      <el-tab-pane label="基本资料" name="basic">
        <el-form :model="profile" ref="profileForm" label-width="100px" :rules="rules">
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="profile.gender">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="2">女</el-radio>
              <el-radio :label="0">保密</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <el-form-item label="生日" prop="birthday">
            <el-date-picker
              v-model="profile.birthday"
              type="date"
              placeholder="选择日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD">
            </el-date-picker>
          </el-form-item>
          
          <el-form-item label="个性签名" prop="signature">
            <el-input
              type="textarea"
              :rows="3"
              placeholder="写一句话介绍自己"
              v-model="profile.signature">
            </el-input>
          </el-form-item>
          
          <el-form-item label="部门" prop="department">
            <el-select v-model="profile.department" placeholder="请选择部门">
              <el-option
                v-for="item in departments"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item label="职位" prop="position">
            <el-input v-model="profile.position" placeholder="请输入职位"></el-input>
          </el-form-item>
          
          <el-form-item label="员工编号" prop="employeeId">
            <el-input v-model="profile.employeeId" placeholder="请输入员工编号"></el-input>
          </el-form-item>
          
          <el-form-item label="入职日期" prop="hireDate">
            <el-date-picker
              v-model="profile.hireDate"
              type="date"
              placeholder="选择入职日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD">
            </el-date-picker>
          </el-form-item>
          
          <el-form-item label="管理区域" prop="managedArea">
            <el-input v-model="profile.managedArea" placeholder="请输入管理区域"></el-input>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="saveProfile">保存</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      
      <el-tab-pane label="工作记录" name="workRecords">
        <div class="empty-data" v-if="!jobRecords.length">
          <el-empty description="暂无工作记录"></el-empty>
        </div>
        <div v-else>
          <div class="record-summary">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-card shadow="hover">
                  <div slot="header">
                    <span>总上岗次数</span>
                  </div>
                  <div class="card-content">
                    <span class="number">{{ getTotalShifts() }}</span>
                    <span>次</span>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="8">
                <el-card shadow="hover">
                  <div slot="header">
                    <span>总工作时长</span>
                  </div>
                  <div class="card-content">
                    <span class="number">{{ getTotalWorkHours() }}</span>
                    <span>小时</span>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="8">
                <el-card shadow="hover">
                  <div slot="header">
                    <span>当前状态</span>
                  </div>
                  <div class="card-content">
                    <el-tag :type="getCurrentStatusType()">{{ getCurrentStatus() }}</el-tag>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </div>
          
          <el-table
            :data="jobRecords"
            style="width: 100%; margin-top: 20px;">
            <el-table-column
              prop="startingDate"
              label="上岗时间"
              width="180">
            </el-table-column>
            <el-table-column
              prop="laidOffTime"
              label="离岗时间"
              width="180">
              <template slot-scope="scope">
                {{ scope.row.laidOffTime || '当前在岗' }}
              </template>
            </el-table-column>
            <el-table-column
              label="状态">
              <template slot-scope="scope">
                <el-tag :type="scope.row.onGuard ? 'success' : 'info'">
                  {{ scope.row.onGuard ? '在岗' : '离岗' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              label="工作时长">
              <template slot-scope="scope">
                {{ calculateWorkHours(scope.row) }} 小时
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
      
      <el-tab-pane label="权限信息" name="permissions">
        <div class="permission-content">
          <el-card shadow="hover" class="permission-card">
            <div slot="header">
              <span>角色信息</span>
            </div>
            <div class="role-info">
              <h3>{{ getRoleName(adminInfo.roleId) }}</h3>
              <p>{{ getRoleDescription(adminInfo.roleId) }}</p>
            </div>
          </el-card>
          
          <el-card shadow="hover" class="permission-card">
            <div slot="header">
              <span>权限列表</span>
            </div>
            <div v-if="permissions.length === 0" class="empty-data">
              <el-empty description="暂无权限信息"></el-empty>
            </div>
            <div v-else>
              <el-tree
                :data="permissions"
                :props="defaultProps"
                show-checkbox
                default-expand-all
                disabled
                node-key="id">
              </el-tree>
            </div>
          </el-card>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'AdminProfile',
  data() {
    return {
      activeTab: 'basic',
      profile: {
        account: '',
        avatar: '',
        gender: 0,
        birthday: '',
        signature: '',
        department: '',
        position: '',
        employeeId: '',
        hireDate: '',
        managedArea: '',
      },
      adminInfo: {
        account: '',
        name: '',
        phone: '',
        email: '',
        roleId: '',
        registerTime: '',
      },
      rules: {
        position: [
          { required: true, message: '请输入职位', trigger: 'blur' }
        ],
        department: [
          { required: true, message: '请选择部门', trigger: 'change' }
        ],
      },
      jobRecords: [],
      avatarUrl: '',
      departments: [],
      permissions: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      roles: [
        { id: 'ADMIN', name: '超级管理员', description: '拥有系统所有权限，可以进行所有操作。' },
        { id: 'MANAGER', name: '管理人员', description: '拥有大部分系统权限，负责日常管理工作。' },
        { id: 'OPERATOR', name: '运营人员', description: '负责系统日常运营和数据维护。' },
      ]
    };
  },
  created() {
    this.getAdminProfile();
    this.getAdminInfo();
    this.getJobRecords();
    this.getDepartmentList();
    this.getPermissionList();
  },
  methods: {
    async getAdminProfile() {
      try {
        const res = await axios.get('/api/adminProfile/getAdminProfile');
        if (res.data && res.data.code === 200) {
          this.profile = res.data.data;
          this.avatarUrl = this.profile.avatar || '';
        } else {
          this.$message.error('获取个人资料失败');
        }
      } catch (error) {
        console.error('获取个人资料失败', error);
        this.$message.error('获取个人资料失败');
      }
    },
    async getAdminInfo() {
      try {
        const res = await axios.get('/api/admin/getAdminInfo');
        if (res.data && res.data.code === 200) {
          this.adminInfo = res.data.data;
        }
      } catch (error) {
        console.error('获取管理员信息失败', error);
      }
    },
    async getJobRecords() {
      try {
        const res = await axios.get('/api/admin/getJobRecords');
        if (res.data && res.data.code === 200) {
          this.jobRecords = res.data.data || [];
        }
      } catch (error) {
        console.error('获取工作记录失败', error);
      }
    },
    async getDepartmentList() {
      try {
        const res = await axios.get('/api/adminProfile/getDepartmentList');
        if (res.data && res.data.code === 200) {
          this.departments = res.data.data || [];
        }
      } catch (error) {
        console.error('获取部门列表失败', error);
      }
    },
    async getPermissionList() {
      try {
        const res = await axios.get('/api/admin/getPermissionsByRole');
        if (res.data && res.data.code === 200) {
          this.permissions = res.data.data || [];
        }
      } catch (error) {
        console.error('获取权限列表失败', error);
      }
    },
    async saveProfile() {
      try {
        this.$refs.profileForm.validate(async (valid) => {
          if (valid) {
            const res = await axios.post('/api/adminProfile/updateProfile', this.profile);
            if (res.data && res.data.code === 200) {
              this.$message.success('个人资料更新成功');
            } else {
              this.$message.error(res.data.msg || '个人资料更新失败');
            }
          } else {
            return false;
          }
        });
      } catch (error) {
        console.error('保存个人资料失败', error);
        this.$message.error('保存个人资料失败');
      }
    },
    resetForm() {
      this.$refs.profileForm.resetFields();
      this.getAdminProfile();
    },
    getRoleName(roleId) {
      const role = this.roles.find(r => r.id === roleId);
      return role ? role.name : '未知角色';
    },
    getRoleDescription(roleId) {
      const role = this.roles.find(r => r.id === roleId);
      return role ? role.description : '';
    },
    getTotalShifts() {
      return this.jobRecords.filter(record => record.onGuard === true).length;
    },
    getTotalWorkHours() {
      return this.jobRecords.reduce((total, record) => {
        return total + this.calculateWorkHours(record);
      }, 0);
    },
    calculateWorkHours(record) {
      if (!record.startingDate) return 0;
      
      const startTime = new Date(record.startingDate).getTime();
      const endTime = record.laidOffTime ? new Date(record.laidOffTime).getTime() : new Date().getTime();
      
      const hours = Math.round((endTime - startTime) / (1000 * 60 * 60));
      return hours > 0 ? hours : 0;
    },
    getCurrentStatus() {
      const currentRecord = this.jobRecords.find(record => record.onGuard === true);
      return currentRecord ? '在岗' : '离岗';
    },
    getCurrentStatusType() {
      return this.getCurrentStatus() === '在岗' ? 'success' : 'info';
    },
    handleAvatarSuccess(res) {
      if (res.code === 200) {
        this.avatarUrl = res.data;
        this.profile.avatar = res.data;
        this.$message.success('头像上传成功');
      } else {
        this.$message.error(res.msg || '头像上传失败');
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/webp';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是JPG/PNG/WEBP格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过2MB!');
      }
      return isJPG && isLt2M;
    },
    handleAvatarError() {
      this.avatarUrl = '';
    }
  }
}
</script>

<style scoped>
.admin-profile {
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 8px;
  min-height: 500px;
}

.profile-header {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
  padding: 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.avatar-container {
  margin-right: 30px;
  text-align: center;
}

.upload-btn {
  margin-top: 10px;
}

.admin-info {
  flex-grow: 1;
}

.admin-role {
  font-size: 16px;
  color: #409EFF;
  font-weight: bold;
  margin-top: 5px;
}

.signature {
  color: #606266;
  font-style: italic;
  margin-top: 5px;
}

.el-tabs {
  margin-top: 20px;
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.empty-data {
  padding: 40px 0;
  text-align: center;
}

.record-summary {
  margin-bottom: 20px;
}

.card-content {
  text-align: center;
  padding: 20px 0;
}

.number {
  font-size: 30px;
  font-weight: bold;
  color: #409EFF;
  margin-right: 5px;
}

.permission-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.permission-card {
  margin-bottom: 20px;
}

.role-info {
  padding: 10px 0;
}

.role-info h3 {
  color: #409EFF;
  margin-top: 0;
}

.role-info p {
  color: #606266;
}
</style> 